package dao;


import hibernate.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import entities.ListaPreciosEntity;
import entities.ProveedorEntity;

public class HibernateListaPreciosBeanDAO 
{
	private static HibernateListaPreciosBeanDAO instancia = null;
	private static SessionFactory sf = null;

	public static HibernateListaPreciosBeanDAO getInstancia()
	{
		if(instancia == null)
		{
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateListaPreciosBeanDAO();
		} 
		return instancia;
	}
	
	public void guardarListaPrecios( ListaPreciosEntity listaPrecios )
	{
		Session session = sf.openSession();
		session.beginTransaction();
		
		session.persist(listaPrecios);
		
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public ListaPreciosEntity obtenerListaPrecios( ProveedorEntity proveedor )
	{	
		Session session = sf.openSession();
		Query query = session.createQuery(	"SELECT lp " +  
											"FROM ListaPreciosBean lp JOIN lp.proveedor prov "  + 
											"WHERE prov.id = :provId" )
											.setLong("provId", proveedor.getId());
		
		ListaPreciosEntity listaPrecios = (ListaPreciosEntity) query.uniqueResult();
		
		return listaPrecios;
	}
	
	@SuppressWarnings("unchecked")
	public List<ListaPreciosEntity> obtenerListasVigentes()
	{
		List<ListaPreciosEntity> listasVigentes;
		
		Session session = sf.openSession();
		session.beginTransaction();
		listasVigentes = session.createQuery( "FROM ListaPreciosBean lp where lp.fechaVencimiento >= GETDATE()").list();
		session.getTransaction().commit();
		session.close();
		return listasVigentes;
	}
}
